<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            display: flex;
            justify-content: center;
        }
        .search input,.search button{
            float: right;
            height: 30px;
            line-height: 30px;
            box-sizing: border-box;
            margin-bottom: 14px;
        }
         
        table{
            border-collapse: collapse;
            width: 700px;

        }
        th,td{
            border:1px solid #ccc;
            padding:14px;
            text-align: center;
        }
    </style>
    <script src="js/jquery.min.js"></script>
</head>
<body>
    <div>
        <div class="search">
            <button>查询</button> <input type="text">
        </div>
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>产品名</th>
                    <th>价格</th>
                </tr>
            </thead>
            <tbody>
    
            </tbody>
        </table>
    </div>

</body>
<script>
    $(function(){
        var data = [{
            id: 1,
            pname: '小米',
            price: 3999
        }, {
            id: 2,
            pname: 'oppo',
            price: 999
        }, {
            id: 3,
            pname: '荣耀',
            price: 1299
        }, {
            id: 4,
            pname: '华为',
            price: 1999
        }];
        var total = 0;
        data.forEach(function(value,index,arry){
            // 创建要追加的节点
            if(value.price < 1000){
                var tr = $('<tr style="color:red"><td>'+value.id+'</td><td>'+value.pname+'</td><td>'+value.price+'</td></tr>');
            }else{
                var tr = $('<tr><td>'+value.id+'</td><td>'+value.pname+'</td><td>'+value.price+'</td></tr>');
            }
            total+=value.price;
            $('tbody').append(tr);
        })
        console.log(total);
        $('tbody').append($('<tr><td colspan="3">总价为：'+total+'</td></tr>'));

        $('button').click(function(){
            // 获取到查询的值
            var inputVal = $('input').val();
            if(inputVal){
                // 清除掉里面的内容
                $('tbody').empty();
                var num = 0;  // 计数器(查找到了多少条数据)
                data.forEach(function(value){
                    if(value.pname.indexOf(inputVal)!=-1){  // 查询到追加value.pname == inputVal,indexOf 返回的是小标
                        var tr = $('<tr><td>'+value.id+'</td><td>'+value.pname+'</td><td>'+value.price+'</td></tr>');
                        $('tbody').append(tr);
                        num++
                    }
                })

                if(!num){
                    $('tbody').append($('<tr><td colspan="3">抱歉，商品正在备货中.........</td></tr>')); 
                }
            }else{
                alert('请输入内容')
            }
            
        })
    })


</script>
</html>